package cn.rubintry.bug.lib.network.http.dialog

import android.app.Dialog
import android.content.Context
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.view.Gravity
import android.view.WindowManager
import androidx.core.content.ContextCompat
import cn.rubintry.bug.lib.network.R
import cn.rubintry.bug.lib.network.databinding.DialogLoadingBinding
import com.blankj.utilcode.util.SizeUtils
import com.wang.avi.AVLoadingIndicatorView
import java.lang.ref.WeakReference

class LoadingDialog(context: Context) : Dialog(WeakReference(context).get()!! , true , {}) {


    private var binding: DialogLoadingBinding? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = DialogLoadingBinding.inflate(layoutInflater)
        binding?.let {
            setContentView(it.root)
        }
    }


    override fun show() {
        //线程校验，确保在当前looper上进行线程调度，否则会引发崩溃
        if(Thread.currentThread() != Looper.myLooper()?.thread){
            Looper.myLooper()?.let { looper ->
                Handler(looper).post(Runnable {
                    makeShow()
                })
            }
            return
        }
        makeShow()
    }

    /**
     * 关闭的同时取消正在重试的请求，重试机制详见[cn.rubintry.bug.lib.network.http.interceptor.NetWorkRetryInterceptor]
     */
    override fun dismiss() {
        super.dismiss()
        binding?.loadingView?.hide()
    }

    /**
     * 弹出弹窗的具体实现
     */
    private fun makeShow() {
        super.show()
        binding?.loadingView?.show()
        window?.clearFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE or WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM)
        // 然后弹出输入法
        window?.decorView?.setPadding(0, 0, 0, 0)
        window?.setGravity(Gravity.CENTER)
        window?.setDimAmount(0f);
        //调整窗体大小
        val params = window?.attributes
        params?.width = SizeUtils.dp2px(60f)
        params?.height = SizeUtils.dp2px(60f)
        window?.setBackgroundDrawable(ContextCompat.getDrawable(context , R.drawable.bg_loading))
        window?.attributes = params
    }
}